package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.dao.TaskDao;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    /**
     *
     * @param taskViewModel
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public Boolean create(TaskViewModel taskViewModel,Integer userId) {
        checkCreateTask(taskViewModel.getInnerCode(),taskViewModel.getProductType());
        if(hasTask(taskViewModel.getInnerCode(),taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }

        TaskEntity task = new TaskEntity();
        BeanUtils.copyProperties(taskViewModel, task);
        // 设置工单编号
        task.setTaskCode(generateNumberByDay());
        // 设置工单类型
        task.setProductTypeId(taskViewModel.getProductType());
        // 工单状态
        task.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        // 设置指派人id
        task.setAssignorId(userId);

        VmVO vm= vmService.getVMInfo(taskViewModel.getInnerCode());

        // 工单执行地址
        task.setAddr(vm.getNodeAddr());
        // 所属区域Id
        task.setRegionId(vm.getRegionId());
        this.save(task);

        //判断工单是否为补货工单
        if(task.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            for (TaskDetailsViewModel detail : taskViewModel.getDetails()) {
                TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(detail,taskDetailsEntity);
                taskDetailsEntity.setTaskId(task.getTaskId());
                taskDetailsService.save(taskDetailsEntity);
            }
        }
        return true;
    }

    @Override
    public boolean accept(Long id) {
        //查询工单
        TaskEntity task = this.getById(id);
        if(task.getTaskStatus()!= VMSystem.TASK_STATUS_CREATE ){
            throw new LogicException("工单状态不是待处理");
        }
        //修改工单状态为进行
        task.setTaskStatus( VMSystem.TASK_STATUS_PROGRESS );
        return this.updateById(task);
    }


    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 更新工单量列表
     * @param taskEntity
     * @param score
     */
    private void  updateTaskZSet(TaskEntity taskEntity,int score){
        String roleCode="1003";//运维员
        if(taskEntity.getProductTypeId().intValue()==2){//如果是补货工单
            roleCode="1002";//运营员
        }
        String key= VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+ taskEntity.getRegionId()+"."+roleCode;
        redisTemplate.opsForZSet().incrementScore(key,taskEntity.getUserId(),score);
    }


    /**
     * 工单校验
     * @param innerCode 设备编号
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(String innerCode,int productType) throws LogicException {

        //根据设备编号查询设备
        VmVO vmInfo = vmService.getVMInfo(innerCode);
        if(vmInfo == null) {
            throw new LogicException("设备校验失败");
        }
        //如果是投放工单，状态为运营
        if(productType == VMSystem.TASK_TYPE_DEPLOY  && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备已在运营");
        }

        //如果是补货工单，状态不是运营状态
        if(productType == VMSystem.TASK_TYPE_SUPPLY  && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }

        //如果是撤机工单，状态不是运营状态
        if(productType == VMSystem.TASK_TYPE_REVOKE  && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }
    }


    /**
     * 同一台设备下是否存在未完成的工单
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode,int productionType){
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode,innerCode)
                .eq(TaskEntity::getProductTypeId,productionType)
                .le(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS);
        return this.count(qw) > 0;
    }

    private static final int LENGTH = 4;
    private static final String DAY_FORMAT = "yyyyMMdd";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * redis生成格式为8位年月日+4位当日序号
     *
     * @return
     */

    public String generateNumberByDay() {
        String month = new SimpleDateFormat(DAY_FORMAT).format(new Date());
        Long number = stringRedisTemplate.opsForValue().increment("" + ":" + month);
        return month + StringUtils.leftPad(number.toString(), LENGTH, '0');
    }


}
